﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace de.wolfmarco.pas.Shared.Database
{
    public class EntityBase : INotifyPropertyChanged
    {
        public EntityBase()
            : base()
        {
        }

        #region Primary key

        /// <summary>Primärschlüssel</summary>
        [Key]
        public Guid Id { get; set; }

        /// <summary>Is it a new Entity, which has not been saved in database?</summary>
        [NotMapped]
        public bool IsNew { get { return Id == Guid.Empty; } }

        #endregion Primary key

        #region Concurrency

        /// <summary>
        /// Optimistic Concurrency (auch: Optimistisches Locking genannt) 
        /// Den parallelen Zugriff von mehreren Benutzern auf denselben Datensatz konfliktarm und ohne Inkonsistenzen zu regeln.
        /// </summary>
        [Timestamp]
        public byte[] RowVersion { get; set; }

        #endregion Concurrency

        #region Entity state

        public void MarkDirty()
        {
            IsDirty = true;
        }

        public void MarkClean()
        {
            IsDirty = false;
        }

        [NotMapped, DefaultValue(false)]
        public bool IsDirty { get; private set; }

        /// <summary>Adds this entity to the given DbSet or updates it.</summary>
        /// <param name="dbSet">System.Data.Entity.DbSet</param>
        public void FetchEntity(DbContext context, DbSet dbSet)
        {
            if(IsNew)
            {
                Id = Guid.NewGuid();
                dbSet.Add(this);
            }
            else if(IsDirty)
            {
                dbSet.Attach(this);
                context.Entry(this).State = EntityState.Modified;
            }
        }

        #endregion Entity state

        #region INotifyPropertyChanged

        protected void RaisePropertyChanged(string prop)
        {
            MarkDirty();

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion INotifyPropertyChanged
    }
}
